<template>
  <div class="container">
      <el-table
        ref="cart"
        :data="goods"
        show-summary
        @selection-change="handleSelectionChange"
        tooltip-effect="dark"
        style="width: 100%">
        <el-table-column
        type="selection"
        width="55">
        </el-table-column>
        <el-table-column
        prop="name"
        label="商品信息"
        width="300">
        </el-table-column>
        <el-table-column
        prop="price_origin"
        label="单价"
        width="120">
        </el-table-column>
        <el-table-column
        prop="amount"
        label="数量"
        width="200">
            <template slot-scope="scope" >
                <el-input-number v-model="scope.row.amount"  @change="changeAmount(scope.row.amount,scope.row)" size="mini" controls-position="right"  :min="1" :max="10"></el-input-number>
            </template>
        </el-table-column>
        <el-table-column
        label="金额"
        width="120"
        show-overflow-tooltip>
            <template slot-scope="scope">
                <div>{{currentPrice(scope.row.price_origin,scope.row.amount)}}</div>
            </template>
        </el-table-column>
        <el-table-column label="操作">
            <template slot-scope="scope">
                <el-button
                size="mini"
                type="danger" plain
                @click.native.prevent="delete(scope.$index, goods)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <div style="margin-top: 20px">
        <el-button @click="deleteSelection()">删除选中商品</el-button>
        <el-button
            type="danger"
            class="buyBtn"
            @click.native.prevent="chooseAddress()">结算</el-button>
    </div>
    <!-- <div>
        <el-dialog title="收货地址" :visible.sync="dialogFormVisible">
        <el-form :model="form">
            <el-form-item label="新增收货地址" :label-width="formLabelWidth">
            <el-input v-model="newAddress" auto-complete="off"></el-input>
            <el-button @click="addAddress()">新增</el-button>
            </el-form-item>
            <el-form-item label="已有地址" :label-width="formLabelWidth">
            <el-select v-model="addressSelected" placeholder="请选择收货地址">
                <el-option v-for="item in addressList" :value="item_aid"></el-option>
            </el-select>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
        </div>
        </el-dialog>
    </div> -->
  </div>
</template>
<script>
import axios from "axios"
export default {
  data(){
      return{
          goods:[],
          isUser:false,
          multipleSelection: [],
          openAddressBox:false,
          newAddress:''
      }
  },
  mounted(){
      if(localStorage.getItem("Booktoken")){
          this.isUser=true
          axios.get('api/user/getCart').then(res=>{
              console.log(res)
              if(res.code==2){
                  console.log(res.msg)
                  this.goods=[...res.data]
                  console.log(this.goods)
              }else{
                  console.log(res.msg)
              }
          })
      }else{
        this.isUser=false
        let goods=JSON.parse(localStorage.getItem("cart"))
        this.goods=[...goods]
      }
  },
  methods:{
      currentPrice(price,amount){
          return price*amount
      },
      changeAmount(v,e){
        //   console.log(this.goods)
        console.log(v)
        console.log(e)
          this.$nextTick(function(){
              if(this.isUser){
                  axios.post('api/user/changeCart',{
                      mid:'update',
                      amount:e.amount,
                      bid:e.b_id,
                      cid:e.c_id
                  }).then(res=>{
                      if(res){
                          console.log('该商品数量更改成功')
                      }else{
                          console.log('该商品数量更改失败')
                      }
                  })
              }else{
                localStorage.setItem('cart',JSON.stringify(this.goods)) // 数据异步更新
                console.log(JSON.parse(localStorage.getItem("cart")))
              }
          })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val;
        console.log(this.multipleSelection)
      },
      deleteSelection() {
        this.multipleSelection.forEach(i => {
            let t=this.goods.findIndex(v=>{
                return v.b_id==i.b_id
            })
            this.delete(t,this.goods)
        });
      },
      delete(index,rows){
          if(this.isUser){
              axios.post('api/user/changeCart',{
                    mid:'delete',
                    bid:rows[index].b_id,
                    cid:rows[index].c_id
                }).then(res=>{
                    if(res){
                        console.log('该商品数量删除成功')
                    }else{
                        console.log('该商品数量删除失败')
                    }
                })
                rows.splice(index,1)
          }else{
            rows.splice(index,1)
            this.$nextTick(()=>{
                localStorage.setItem('cart',JSON.stringify(this.goods))  
            })
          }    
      },
      chooseAddress(){
          this.openAddressBox=true
          if(localStorage.getItem("Booktoken")){
              this.buy(this.multipleSelection)
          }else{
              alert('请先登录哦~')
          }
          
      },
      buy(row){
            if(this.multipleSelection.length){
                console.log(this.multipleSelection.length)
                console.log(row)
                if(localStorage.getItem("Booktoken")){
                let amount=this.multipleSelection.map(row=>row.amount).reduce((a,c)=>(a+c),0)
                let total=this.multipleSelection.map(row=>row.price_origin*row.amount).reduce((a,c)=>(a+c),0)
                this.multipleSelection.forEach(i => {
                    return Object.assign(i,{total:i.amount*i.price_origin})
                });
                console.log(this.multipleSelection)
                axios.post('api/user/addOrder',{
                        aid:1,
                        amount:amount,
                        total:total,
                        goods:this.multipleSelection
                }).then(Response=>{
                    console.log(Response);
                    if(Response.code===2){
                        this.multipleSelection.forEach(i => {
                            let t=this.goods.findIndex(v=>{
                                return v.b_id==i.b_id
                            })
                            this.delete(t,this.goods)
                        });
                        this.$router.push('/order/'+Response.data)
                    }else{
                        alert(Response.msg);
                    }
                })
            }else{
                this.$alert('登录信息已过期，请重新登录', {
                    confirmButtonText: '确定',
                    callback: () => {
                        this.$router.push('/cart')
                    }
                });
            }
          }else{
              this.$alert('购物车还没有东西哦', {
                confirmButtonText: '确定'
              });
          } 
      }
  }
}
</script>
<style scoped>
.container{
    width: 75%;
    margin: 0 auto;
    padding-top: 7.5em
}
.buyBtn{
    float: right;
    width: 120px;
    margin-right: 75px;
}
</style>
